[C/C++] Process和Thread

前言

作業系統作業要求使用Process和Thread來完成輸出1到10的任務。

Process

在Windows底下得使用CreateProcess,假設輸出是照順序的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
char *link = argv[0] ;
LPTSTR szCmdline = _tcsdup(TEXT(link));
LPTSTR szParam ;
int i = 0 ;
if ( argc == 1 ){
strcat(link," 0") ;
szParam = _tcsdup(TEXT(link)) ;
} else {
char buffer[100] ;
i = atoi(argv[1]) + 1 ;
itoa(i,buffer,10) ;
strcat(link," ") ;
strcat(link,buffer) ;
szParam = _tcsdup(TEXT(link)) ;
}
if ( i < 10 ){
if( !CreateProcess(szCmdline,szParam,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi ) ) {
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
printf("id = %d , output i = %d\n", GetCurrentProcessId() , i );
}
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}

Thread

假設輸出要求照順序,需要互斥鎖來避免Race Condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <windows.h>
int i ;
int flag[2] = {0,0} ;
int turn ;
void printOutput(int n)
{
do {
flag[n] = 1 ;
turn = 1 - n ;
while ( flag[1-n] == 1 && turn == 1-n ) ;
if ( i >= 10 )
return ;
printf("thread %d , output i = %d\n", n + 1 , i);
i ++ ;
flag[n] = 0 ;
} while ( i < 10 );
}
int main()
{
i = 0 ;
HANDLE hThread , hThread2;
unsigned threadID , threadID2;
hThread = (HANDLE)_beginthreadex(NULL, 0, &printOutput, 0 , 0, &threadID);
hThread2 = (HANDLE)_beginthreadex(NULL, 0, &printOutput, 1 , 0, &threadID2);
WaitForSingleObject(hThread, INFINITE);
WaitForSingleObject(hThread2, INFINITE);
CloseHandle(hThread2);
CloseHandle(hThread);
}